package org.rcy.framework.storage.strategy;

import org.rcy.framework.api.storage.StorageStrategy;
import org.rcy.framework.storage.HuaweiCloudObsService;

import javax.crypto.Cipher;
import javax.crypto.NullCipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author 吴康桥
 * @Description
 * @date 2023/7/4 11:26
 */


public class HuaweiCloudStorageStrategy implements StorageStrategy {

	private static final String ALGORITHM = "AES";
	private HuaweiCloudObsService privBucket;
	private HuaweiCloudObsService publicBucket;

	public HuaweiCloudStorageStrategy(HuaweiCloudObsService privBucket,HuaweiCloudObsService publicBucket) {
		this.publicBucket = publicBucket;
		this.privBucket = privBucket;
	}

	@Override
	public String uploadFile(InputStream is, long size) {
		String fileKey = generateFileKey();
		this.privBucket.uploadFile(fileKey,is,size);
		return fileKey;
	}

	@Override
	public boolean uploadPublicFile(InputStream is, String fileKey, long size) {
		this.publicBucket.uploadFile(fileKey,is,size);
		return true;
	}

	@Override
	public InputStream downloadFile(String fileKey) throws IOException {
		InputStream inputStream = this.privBucket.downloadFile(fileKey);
		return inputStream;
	}

	private static void safeClose(Closeable closeable) {
		if (closeable != null) {
			try {
				closeable.close();
			} catch (IOException var2) {
			}
		}

	}

	private Cipher getCipher(String secretKey) {
		try {
			Cipher cipher = Cipher.getInstance("AES");
			cipher.init(2, new SecretKeySpec(secretKey.getBytes("UTF-8"), "AES"));
			return cipher;
		} catch (Exception var4) {
			return new NullCipher();
		}
	}

	@Override
	public InputStream downloadFile(String fileKey, String secret) throws IOException {
		return this.privBucket.downloadFile(fileKey,getCipher(secret));
	}

	private String generateFileKey() {
		return UUID.randomUUID().toString().replace("-","");
	}
}
